// 会话状态管理

import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { Session } from '@/types/chat';
import { SessionStorage } from '@/utils/storage';

export const useSessionStore = defineStore('session', () => {
  // 状态
  const sessions = ref<Session[]>(SessionStorage.getSessions());
  const activeSessionId = ref<string | null>(null);

  // 动作
  const setSessions = (newSessions: Session[]) => {
    sessions.value = newSessions;
    SessionStorage.setSessions(newSessions);
  };

  const addSession = (session: Session) => {
    sessions.value.unshift(session);
    SessionStorage.setSessions(sessions.value);
  };

  const removeSession = (sessionId: string) => {
    sessions.value = sessions.value.filter(s => s.id !== sessionId);
    if (activeSessionId.value === sessionId) {
      activeSessionId.value = null;
    }
    SessionStorage.setSessions(sessions.value);
  };

  const updateSession = (sessionId: string, updates: Partial<Session>) => {
    const session = sessions.value.find(s => s.id === sessionId);
    if (session) {
      Object.assign(session, updates);
      SessionStorage.setSessions(sessions.value);
    }
  };

  const setActiveSession = (sessionId: string) => {
    activeSessionId.value = sessionId;
  };

  const clearSessions = () => {
    sessions.value = [];
    activeSessionId.value = null;
    SessionStorage.removeSessions();
  };

  return {
    sessions,
    activeSessionId,
    setSessions,
    addSession,
    removeSession,
    updateSession,
    setActiveSession,
    clearSessions
  };
});